package cn.ctvonline.android.kaopu.fragment;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tendcloud.tenddata.TCAgent;

import java.util.ArrayList;
import java.util.List;

import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.AppApplication;
import cn.ctvonline.android.kaopu.base.IncomingHandler;
import cn.ctvonline.android.kaopu.base.MessageHandleListener;
import cn.ctvonline.android.kaopu.constant.TakingEvent;
import cn.ctvonline.android.kaopu.entity.HomeEntity;

/**
 * Created by dujian on 15/11/24.
 */
public class GroupFragment extends LazyBaseFragment {
    static final String TAG = GroupFragment.class + "";
    private SwipeRefreshLayout mHomeSrl;
    private RecyclerView mHomeRv;
    private boolean loadingData = false;

    static final int LOAD_DATA_STYLE_IDLE = 0x00;
    static final int LOAD_DATA_STYLE_REFERSH = 0x01;
    static final int LOAD_DATA_STYLE_LOADMORE = 0x02;
    private int loadDataStyle = LOAD_DATA_STYLE_IDLE;

    private int pageNum = 1;
    private IncomingHandler handler;
    static final int REFERSH_DATA_OK = 0x01;
    static final int LOAD_DATA_OK = 0x02;
    static final int REFERSH_DATA_FAILED = 0x03;
    static final int LOAD_DATA_FAILED = 0x04;
    static final int NO_MORE_DATA = 0x05;
    static final int NO_FRESH_DATA = 0x06;
    private int refershDistance;
    private List<HomeEntity> entities;
    private HomeAdapter mHomeAdapter;
    private LinearLayoutManager linearLayoutManager;
    private boolean autoRefersh = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View parentView = inflater.inflate(R.layout.fragment_group, container, false);
        findViews(parentView);
        initHandler();
        initViews();
        return parentView;
    }

    private void initHandler() {
        handler = getHandler();
        handler.setOnMessageHandleListener(new MessageHandleListener() {
            @Override
            public void onHandlerMessage(Message msg) {
                switch (msg.what) {
                    case LOAD_DATA_OK: {
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        Toast.makeText(activity, "数据加载成功", Toast.LENGTH_SHORT).show();
                        List<HomeEntity> list = (List<HomeEntity>) msg.obj;
                        entities.addAll(list);
                        mHomeAdapter.notifyDataSetChanged();
                    }
                    break;
                    case LOAD_DATA_FAILED:
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        break;
                    case REFERSH_DATA_OK: {
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        Toast.makeText(activity, "数据更新成功", Toast.LENGTH_SHORT).show();
                        List<HomeEntity> list = (List<HomeEntity>) msg.obj;
                        entities.clear();
                        entities.addAll(list);
                        mHomeAdapter.notifyDataSetChanged();
                    }
                    break;
                    case NO_MORE_DATA: {
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        Toast.makeText(activity, "无更多数据", Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case NO_FRESH_DATA: {
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        Toast.makeText(activity, "无更新数据", Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case REFERSH_DATA_FAILED:
                        loadingData = false;
                        mHomeSrl.setRefreshing(loadingData);
                        break;
                }
                loadDataStyle = LOAD_DATA_STYLE_IDLE;
            }
        });
    }

    private void findViews(View view) {
        mHomeSrl = (SwipeRefreshLayout) view.findViewById(R.id.home_srl);
        mHomeRv = (RecyclerView) view.findViewById(R.id.home_rv);
    }

    public void initViews() {
        mHomeSrl.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimaryDark, android.R.color.holo_orange_light);
        // 这句话是为了，第一次进入页面的时候显示加载进度条
        refershDistance = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics());
        mHomeSrl.setProgressViewOffset(false, 0, refershDistance);

//        mHomeSrl.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorPrimary));
        mHomeSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i(TAG, "try to refersh data");
                loadDataStyle = LOAD_DATA_STYLE_REFERSH;
                lazyLoadData();
            }
        });
        mHomeRv.setHasFixedSize(true);
        mHomeRv.setItemAnimator(new DefaultItemAnimator());
        mHomeRv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            int visiableCount = 0;
            int firstVisiablePosi = 0;
            int totalCount = 0;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        break;

                    case RecyclerView.SCROLL_STATE_SETTLING:
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                totalCount = linearLayoutManager.getItemCount();
                visiableCount = linearLayoutManager.getChildCount();
                firstVisiablePosi = linearLayoutManager.findFirstVisibleItemPosition();
                if (firstVisiablePosi > 0 && (visiableCount + firstVisiablePosi >= totalCount) && !loadingData) {
                    Log.i(TAG, "try to load more data, visiableCount=" + visiableCount + ",firstVisiablePosi" + firstVisiablePosi + ",totalCount" + totalCount);
                    //使底部加载view可见
                    loadDataStyle = LOAD_DATA_STYLE_LOADMORE;
                    lazyLoadData();
                }
            }
        });
        entities = new ArrayList<HomeEntity>();
        linearLayoutManager = new LinearLayoutManager(activity);
        mHomeRv.setLayoutManager(linearLayoutManager);
        mHomeAdapter = new HomeAdapter();
        mHomeRv.setItemAnimator(new DefaultItemAnimator() {
            @Override
            public boolean animateRemove(RecyclerView.ViewHolder holder) {
                HomeAdapter.ViewHolder vh = (HomeAdapter.ViewHolder) holder;
                vh.itemView.animate().alpha(0).translationY(0).start();
                return super.animateRemove(holder);
            }

            @Override
            public boolean animateAdd(RecyclerView.ViewHolder holder) {
                HomeAdapter.ViewHolder vh = (HomeAdapter.ViewHolder) holder;
                vh.itemView.animate().alpha(1).translationY(1).start();
                return super.animateAdd(holder);
            }
        });
        mHomeRv.setAdapter(mHomeAdapter);
        mHomeRv.addItemDecoration(new GroupItemDecoration());
    }

    //    /**
//     *
//     * @param alwaysRefersh true则每次都刷新，false则当列表为空或者第一个item可见时刷新
//     */
//    public void doRefersh(boolean alwaysRefersh){
//        Log.i(TAG, "this is do refersh method alwaysRefersg = " + alwaysRefersh);
//        if((!alwaysRefersh && mHomeAdapter.getItemCount() == 0)
//                || alwaysRefersh){
//            loadDataStyle = LOAD_DATA_STYLE_REFERSH;
//            lazyLoadData();
//            Log.i(TAG, "this is do refersh method alwaysRefersg = " + alwaysRefersh+", and do refersh with condition");
//        }
//    }
    protected synchronized void lazyLoadData() {
        Log.i(TAG, "this is lazyLoadData method, loadingData=" + loadingData);
        if (!loadingData) {
            loadingData = true;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    try {
                        List<HomeEntity> list = new ArrayList<HomeEntity>();
                        //刷新
                        if (loadDataStyle == LOAD_DATA_STYLE_REFERSH) {
                            pageNum = 1;
                            if (Math.random() < 0.2f) {
                                msg.what = NO_FRESH_DATA;
                            } else {
                                for (int i = 0; i < 10; i++) {
                                    HomeEntity entity = new HomeEntity();
                                    int flag = (pageNum - 1) * 10 + i;
                                    entity.setIntro("这是刷新，第" + flag + "次的简介");
                                    list.add(entity);
                                }
                                msg.what = REFERSH_DATA_OK;
                            }
                        } else if (loadDataStyle == LOAD_DATA_STYLE_LOADMORE) {//加载更多
                            if (pageNum < 3) {
                                for (int i = 0; i < 10; i++) {
                                    HomeEntity entity = new HomeEntity();
                                    int flag = (pageNum - 1) * 10 + i;
                                    entity.setIntro("这是加载更多，第" + flag + "次的简介,pageNum=" + pageNum);
                                    list.add(entity);
                                }
                                pageNum += 1;
                                msg.what = LOAD_DATA_OK;
                            } else {
                                msg.what = NO_MORE_DATA;
                            }
                        }
                        msg.obj = list;
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(msg);
                }
            }).start();
        }
    }

    /**
     * <p/>
     * viewHolder =  inflater.inflate(R.layout.home_list_item, parent, false);
     */
    class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private LayoutInflater inflater;

        public HomeAdapter() {
            inflater = LayoutInflater.from(activity);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.group_list_item, parent, false);
            ViewHolder vh = new ViewHolder(view);
            return vh;
        }

        @Override
        public int getItemCount() {
            return entities.size();
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ViewHolder vh = (ViewHolder) holder;
            HomeEntity entity = entities.get(position);
            String imageUrl = entity.getImageUrl();
            DisplayImageOptions options = AppApplication.getInstance().getOptions();
            ImageLoader.getInstance().displayImage(imageUrl, vh.introIv, options);
            vh.introTv.setText(entity.getIntro());
            vh.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TCAgent.onEvent(activity, TakingEvent.CLICK_ENENT_ID + "", " homeFragment item click");
                    Toast.makeText(activity, "item clicked", Toast.LENGTH_SHORT).show();
                }
            });
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView introIv;
            TextView introTv;

            ViewHolder(View view) {
                super(view);
                introIv = (ImageView) view.findViewById(R.id.home_intro_iv);
                introTv = (TextView) view.findViewById(R.id.home_intro_tv);
            }
        }
    }

    class GroupItemDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            Paint paint = new Paint();
            paint.reset();
            paint.setColor(parent.getResources().getColor(R.color.gray_light));
            paint.setStrokeWidth(2);
            paint.setStyle(Paint.Style.STROKE);
            paint.setAntiAlias(true);
            int count = parent.getChildCount();
            for (int i = 0; i < count; i++) {
                View itemView = parent.getChildAt(i);
                float x = itemView.getX();
                float y = itemView.getY();
                int width = itemView.getWidth();
                int height = itemView.getHeight();
                c.drawLine(x, y, x + width, y, paint);
                c.drawLine(x, y + height, x + width, y + height, paint);
            }
            super.onDraw(c, parent, state);
        }
    }
}
